import { _decorator,sys, Component, error, Node, Prefab, resources } from 'cc';
import { AdComponent } from './AdComponent';
import *as cc from "cc";
import { WECHAT } from 'cc/env';
import { KuaishouAdAdapter } from './KuaishouAdAdapter';

const wx = (window as any).wx;
const { ccclass, property } = _decorator;

@ccclass('Util')
export default class Util {
  //创建本类的全局调用变量
  public static _instance: Util = null
  public static get Instance() {
    if (null == this._instance) {
      this._instance = new Util();
    }
    return this._instance;
  }

  //关卡模式
  mainGameLevelMode: number = 1;
  //是否游戏结束
  isGameOver: boolean = false;
  //插屏是否可以显示
  isShowInster: boolean = true;


  // 秒数转换
  formatSeconds(seconds: number | string, dateFormat = 'h:i:s'): string {
    seconds = Number(seconds)
    let obj: any = {}
    obj.h = Number.parseInt(String(seconds / 3600));
    obj.i = Number.parseInt(String((seconds - obj.h * 3600) / 60));
    obj.s = Number.parseInt(String(seconds - obj.h * 3600 - obj.i * 60));
    if (obj.h < 10) obj.h = '0' + obj.h;
    if (obj.i < 10) obj.i = '0' + obj.i;
    if (obj.s < 10) obj.s = '0' + obj.s;
    // 3.解析
    var rs = dateFormat.replace('h', obj.h).replace('i', obj.i).replace('s', obj.s);
    return rs;
  }
  getTimeByScend(num: number): { hour: string, min: string, scend: string } {
    if (!num || num < 0) return { hour: '00', min: "00", scend: "00" };
    num = Math.ceil(num);
    let hour = 0;
    let min = 0;
    let scend = num;

    hour = Math.floor(num / 3600);
    min = Math.floor(num / 60) - hour * 60;
    scend = num - hour * 3600 - min * 60;

    let hourStr = hour >= 10 ? "" + hour : "0" + hour;
    let minStr = min >= 10 ? "" + min : "0" + min;
    let scendStr = scend >= 10 ? "" + scend : "0" + scend;

    return { hour: hourStr, min: minStr, scend: scendStr };

  }
  /**加载预制体 */
  GloberLoadPrefab(prefab_name: string = 'no', type: number, call: Function, fail?: Function) {
    if (type == 1) {
      //加载炮塔预制体
      resources.load(`prefabs/Home/` + prefab_name, Prefab, (err, res) => {
        if (err) {
          error("加载资源失败", err);
          fail && fail();
          return;
        }
        call && call(res);
      })
    } else if (type == 2) {
      //加载炮塔预制体
      resources.load(`prefabs/MainGame/` + prefab_name, Prefab, (err, res) => {
        if (err) {
          error("加载资源失败", err);
          fail && fail();
          return;
        }
        call && call(res);
      })
    }

  }

  /**自动插屏广告 */
  autoShowInsterAd() {
    console.log('插屏广告已禁用');
    return;
    // setInterval(() => {
    //   AdComponent.Instance.autoShowInsterAd();
    // }, 65000);

  }

  /**插屏广告间隔 */
  insterAdCountDown() {
    setInterval(() => {
      this.isShowInster = true;
    }, 60000);
  }


  //#region 本地储存
    /**设置本地储存前缀*/
    private prefix:string="game";
    /**储存数据 */
    set(key, value){
      let fkey = this.prefix + key;
      if(WECHAT){
        wx.setStorage({
            key:fkey,
            data:value
        })
      }else{
        cc.sys.localStorage.setItem(fkey, value);
      }
    }
    /**获取数据*/
    get(key){
          let fkey = this.prefix + key;
          if(WECHAT){
              return  wx.getStorageSync(fkey);
          }else{
              return cc.sys.localStorage.getItem(fkey);
          }
    }
    /**删除所有本地数据*/
    removeAllData(){
          if(WECHAT){
              wx.clearStorage();
          }else{
              cc.sys.localStorage.clear();
          }
    }
    //#endregion

  //#region 微信模块 
      /**微信广告id*/
      VideoUrl:string="adunit-1154dd381e38ee4c";
      /**广告*/
      Video:any=null;  
      /**广告播放关卡 */  
      VideoLv:number=0;
      VideoNum:number=0;  //1打开某一关  2 打开某一页  3看提示  4  看答案   5是游戏过程加时间    6是失败加时间
      /**处理回调集合 */
      handlers:any={};
      isVideo:number=2;
      tanchu:boolean=false;
      closeType:number=-1;
      /**创建视频广告*/
      InitVideoAdvert(){
          if(WECHAT){//微信
            var self=this;
            if(self.Video==null){
                self.Video=wx.createRewardedVideoAd({
                    adUnitId: self.VideoUrl
                });
                //广告播放错误
                self.Video.onError(err => {
                    if(self.handlers[self.VideoNum]!=null){
                        self.handlers[self.VideoNum](false);
                    }
                });
                //广告播放关闭
                self.Video.onClose((res)=>{
                    if (res && res.isEnded || res === undefined) {//播放完毕
                        if(self.handlers[self.VideoNum]!=null){
                            self.handlers[self.VideoNum](true);
                        }
                        
                    }
                    else {//播放中途退出，不下发游戏奖励
                      if(self.handlers[self.VideoNum]!=null){
                        self.handlers[self.VideoNum](false);
                      }
                    }
                });
            }
          }
       }
      //播放广告
      VideoPlay(videonum,fn,Lv=0){
           // 检查是否为快手环境
           if (typeof (window as any).ks !== 'undefined') {
               console.log('使用快手激励视频广告替代微信视频广告');
               KuaishouAdAdapter.Instance.showRewardedVideoAd(fn);
               return;
           }
           
           // 非快手环境，直接返回成功
           console.log('非快手环境，模拟视频广告播放成功');
           setTimeout(() => fn(true), 100);
           return;
           
           if(!WECHAT){
              fn(true);
              return;
           }
           try{
               if(this.Video!=null){
                   this.tanchu=false;
                   this.VideoLv=Lv;
                   this.VideoNum=videonum;
                   this.closeType=videonum;
                   this.addHandlers(videonum+'',fn);
                   this.Video.show();
               }else{
                   fn(false);
               }
           }catch{
               fn(false);
           }
           
       }
      addHandlers(event,fn){
          this.handlers[event]=fn;
      }   
       
        /**右上角分享打开*/
      openshare(){
          if(WECHAT){
              return true;
          }
          wx.onShareAppMessage(() => {
              return {
                title: "据说只有0.01%的人才能过关！",
                imageUrl: 'share.jpg' // 图片 URL
              }
          })
          wx.showShareMenu({
              withShareTicket: true,
              menus: ['shareAppMessage', 'shareTimeline']
          })
      }
      /**分享*/
      share(){
          // 快手环境下使用激励广告替代分享
          if (typeof (window as any).ks !== 'undefined') {
              console.log("快手环境：使用激励广告替代分享功能");
              KuaishouAdAdapter.Instance.simulateShare();
              return;
          }
          
          if(WECHAT){
              console.log("分享");
              wx.shareAppMessage({
                  title:"兔了个兔，第三关太难了",
                  imageUrl: 'Res/share.png',
              });
          } else {
              console.log("非微信环境，模拟分享成功");
          }
      }
  //#endregion

}


